import { GetUserInfo, UserRegisterInfo, UserShareInfo } from '@/api/user';
import { Button } from '@antmjs/vantui';
import { Image, Input, Text, View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { useSetState } from 'ahooks';
import { useRequest } from 'taro-hooks';

import SwitchIdentities from '@/components/SwitchIdentities';
import { TemplateMessage } from 'types/user';

export default function Page() {
  //根据推荐吗获取分享人信息
  const referCode = Taro.getStorageSync('refer_code');

  useRequest(
    () =>
      UserShareInfo({
        code: referCode,
      }),
    {
      ready: referCode ? true : false,
      onSuccess: function (data) {
        data?.name && setFormDatas({ reg_name: data?.name });
        referCode && setFormDatas({ reg_code: referCode });
      },
    }
  );

  const router = useRouter();
  const { runAsync, loading } = useRequest(UserRegisterInfo, {
    manual: true,
  });

  const [formDatas, setFormDatas] = useSetState<{
    headimg: string | undefined;
    name: string | undefined;
    phone: string | undefined;
    company: string | undefined;
    reg_code: string | undefined;
    reg_name: string | undefined;
  }>({
    headimg: undefined,
    name: undefined,
    phone: router?.params?.phone || undefined,
    company: undefined,
    reg_code: router?.params?.regCode || undefined,
    reg_name: router?.params?.regName || undefined,
  });

  useRequest(GetUserInfo, {
    cacheKey: 'get:user:info',
    onSuccess: function (data) {
      if (!data) return;
      setFormDatas({
        phone: data?.phone,
        headimg: data.headimg,
        name: data.name,
        company: data.company,
      });
    },
  });

  return (
    <View
      className='min-h-screen overflow-hidden relative bg-no-repeat pb-[80px]'
      style={{
        backgroundImage:
          'url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/info-bg.jpg)',
        backgroundSize: '100% auto',
      }}
    >
      <View className=' absolute right-2 top-2'>
        <SwitchIdentities />
      </View>

      {/* avatar */}
      <View
        className='w-[222px] h-[222px] rounded-full bg-[#EDEDED] my-[64px] mx-auto shadow-2xl border-8 border-white relative'
        onClick={async () => {
          const res = await Taro.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album'],
          });

          const filePath = res?.tempFilePaths[0];
          const { data } = await Taro.uploadFile({
            url: `${APP_API_URL}/api/user/upload`,
            filePath,
            name: 'file',
            header: {
              openId: Taro.getStorageSync('openId'),
              token: Taro.getStorageSync('token'),
            },
          });

          if (!data) return;
          const headimg = JSON.parse(data)?.data;
          if (!headimg) return;
          setFormDatas({
            headimg,
          });
        }}
      >
        {(formDatas.headimg && (
          <Image
            mode='aspectFill'
            src={formDatas.headimg}
            className=' w-full h-full rounded-full object-cover'
          />
        )) || (
          <View
            className='w-[116px] h-[116px] bg-cover absolute  left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2'
            style={{
              backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-photo.svg)`,
            }}
          ></View>
        )}
        <View className=' text-xs text-primary rounded-full w-[124px] leading-[48px] text-center border-2 border-primary bg-gary2 absolute bottom-0 left-1/2 -translate-x-1/2 translate-y-[24px]'>
          上传头像
        </View>
      </View>

      <View className='w-[710px] mx-auto rounded-md  bg-[rgba(255,255,255,0.9)] backdrop-blur-md shadow-2xl pt-6'>
        <Text className=' block text-center text-lg text-black font-bold'>
          登录成功，请完善信息
        </Text>
        <Text className=' block text-xs text-gary1 text-center mb-[52px] mt-1'>
          完善信息审核通过后您将可以体验平台全部服务
        </Text>

        <View className='w-[610px] mx-auto'>
          <Input
            value={formDatas.name}
            className='h-[104px]  focus:border-primary border-gary2 border-solid border-2 p-4'
            type='text'
            placeholder='姓名 *'
            onInput={(e) => {
              setFormDatas({
                name: e.detail.value,
              });
            }}
          />

          <Input
            value={formDatas.phone}
            className='h-[104px]  focus:border-primary border-gary2 border-solid border-2 p-4 mt-3 disabled:bg-gary2'
            type='number'
            disabled
            placeholder='手机号'
          />

          <Input
            value={formDatas.company}
            className='h-[104px]  focus:border-primary border-gary2 border-solid border-2 p-4 mt-3'
            type='text'
            placeholder='公司名称'
            onInput={(e) => {
              setFormDatas({
                company: e.detail.value,
              });
            }}
          />

          <Input
            className='h-[104px]  focus:border-primary border-gary2 border-solid border-2 p-4 mt-3'
            type='text'
            placeholder='推荐人'
            value={formDatas.reg_name}
            onInput={(e) => {
              setFormDatas({
                reg_name: e.detail.value,
              });
            }}
          />

          <Input
            className='h-[104px]  focus:border-primary border-gary2 border-solid border-2 p-4 mt-3'
            type='text'
            placeholder='推荐码'
            value={formDatas.reg_code}
            onInput={(e) => {
              setFormDatas({
                reg_code: e.detail.value,
              });
            }}
          />

          <Button
            loading={loading}
            type='primary'
            className='w-[420px] h-[92px] leading-[92px] block mt-[138px] translate-y-[46px]'
            onClick={async () => {
              if (!formDatas.name)
                return Taro.showToast({ title: '请输入姓名', icon: 'none' });
              if (!formDatas.company)
                return Taro.showToast({
                  title: '请输入公司名称',
                  icon: 'none',
                });

              //@ts-ignore
              await Taro.requestSubscribeMessage({
                tmplIds: [TemplateMessage.审核结果通知],
              });

              await runAsync({
                name: formDatas.name,
                company: formDatas.company,
                reg_code: formDatas.reg_code,
                reg_name: formDatas.reg_name,
                headimg: formDatas.headimg,
              });

              Taro.showToast({ title: '提交成功', icon: 'success' });
              Taro.redirectTo({
                url: '/pages/info/success',
              });
            }}
          >
            提交信息
          </Button>
        </View>
      </View>
    </View>
  );
}
